'use strict'

// As early as possible in your application
// require and configure dotenv
require('dotenv').config()

// add env config default 'development'
// NODE_ENV=production node app.js
// will result the `env` equal 'production'
let env = process.env.NODE_ENV || 'development'

const koa = require('koa')
const logger = require('koa-logger')
const jsonp = require('koa-safe-jsonp')
const auth = require('koa-basic-auth')
var serve = require('koa-static')
// api v1
const v1 = require('./api/v1')
const v2 = require('./api/v2')

const app = koa()
// logger middleware
app.use(logger())
app.use(serve('./public'))

// jsonp response
// usage this.jsonp=
jsonp(app)

app.use(function* (next) {
  try {
    yield next
  }
  catch (err) {
    this.status = err.status || 500
    this.type = 'json'
    this.body = {
      error: true,
      msg: (env !== 'production' && err.message) || 'An error occured',
    }
  }
})

// app.use(auth({ name: process.env.BASIC_AUTH_USERNAME, pass: process.env.BASIC_AUTH_PASSWORD }))

// use api v1 routes middleware
app.use(v1.routes())
app.use(v2.routes())

app.use(function* pageNotFound(next) {
  // we need to explicitly set 404 here
  // so that koa doesn't assign 200 on body=
  this.status = 404

  switch (this.accepts('html', 'json')) {
    case 'html':
      this.type = 'html'
      this.body = '<p>Page Not Found</p>'
      break
    case 'json':
      this.body = {
        error: true,
        msg: '404 Not Found'
      }
      break
    default:
      this.type = 'text'
      this.body = 'Page Not Found'
  }
})

process.on('unhandledRejection', (reason, p) => {
  console.log('Unhandled Rejection at: Promise')
  console.log(p)
  console.log('reason:', reason)
})

process.on('uncaughtException', (err) => {
  console.log(`Caught exception: ${err}`)
  process.exit(1)
})

// when require this module
// from other moudle will not start the server
if (!module.parent) {
  app.listen(process.env.PORT || 8080)
}

module.exports = app
